import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Form,
  message,
  Input,
  InputNumber,
  Checkbox,
  Tabs,
  Table,
  Space,
  Popconfirm,
  Row,
  Col,
  Select,
  Divider,
} from 'antd';
import request from '@/utils/request';
import CateSelect from '@/components/CategoryComponent';
import { FormattedMessage, useIntl } from 'umi';

const apiURL = '/api/services/app/ERPReports/';
const { TabPane } = Tabs;

const DataDesignForm = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [record, setRecord] = useState({});
  const [act, setAct] = useState('Create');
  const [defTab, setDefTab] = useState('1');
  const [dicType, setDicType] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  const onFinish = (values: any) => {
    setLoading(true);
    let items: any = [];
    values.width = values.width ? values.width : 60;
    console.log(values);

    if (act === 'Create') {
      values.id = new Date().getTime();
      setDataSource([...dataSource, values]);
      items = [...dataSource, values];
    } else {
      items = dataSource.map((element: any) => {
        if (element.id === values.id) {
          return values;
        } else {
          element.width = element.width ? element.width : 60;
          return element;
        }
      });
      setDataSource(items);
    }
    doSave(props.data, items);
    setLoading(false);
  };

  const doDel = (id: any) => {
    const items = dataSource.filter((item: any) => item.id != id);
    setDataSource(items);
    doSave(props.data, items);
  };

  const doSave = (record: any, fielDefine: any) => {
    record.fielDefine = JSON.stringify(fielDefine);
    if (Array.isArray(record.authUsers)) {
      record.authUsers = record.authUsers.join(',');
    }
    request(apiURL + 'Update', {
      method: 'PUT',
      data: record,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.save.success' }));
        }
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    try {
      const datas = JSON.parse(props.data?.fielDefine);
      if (Array.isArray(datas)) {
        setDataSource(datas);
      }
      fetchLayout();
    } catch {}
  }, []);

  const fetchLayout = () => {
    request('/api/services/app/Category/GetLayouts', {
      method: 'GET',
    }).then((response) => {
      if (response) {
        if (response.success) {
          const dicType: any = [];
          response.result.forEach((item: any) => {
            dicType.push({
              label: item,
              value: item,
            });
          });
          setDicType(dicType);
        }
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const setCurrent = (record: any) => {
    setRecord(record);
    setDefTab('2');
    setAct('Update');
    formRef.current.resetFields();
    formRef.current.setFieldsValue(record);
  };

  const newData = () => {
    setAct('Create');
    formRef.current.resetFields();
  };

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.order' }),
      dataIndex: 'order',
    },
    {
      title: intl.formatMessage({ id: 'pages.fieldName' }),
      dataIndex: 'dataIndex',
    },
    {
      title: intl.formatMessage({ id: 'pages.displayName' }),
      dataIndex: 'title',
    },
    {
      title: intl.formatMessage({ id: 'pages.fieldType' }),
      dataIndex: 'valueType',
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      key: 'action',
      width: 180,
      render: (_: any, record: any) => (
        <span>
          <Button size="small" type="link" onClick={() => setCurrent(record)}>
            {intl.formatMessage({ id: 'pages.edit' })}
          </Button>
          <Divider type="vertical" />
          <Popconfirm title={intl.formatMessage({ id: 'pages.confirmDelete' })} onConfirm={() => doDel(record.id)}>
            <Button size="small" type="link" danger>
              {intl.formatMessage({ id: 'pages.delete' })}
            </Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <>
      <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
        <TabPane tab={intl.formatMessage({ id: 'pages.fieldList' })} key="1">
          <Table
            loading={loading}
            rowKey="id"
            key="id"
            columns={columns}
            dataSource={dataSource}
            onRow={(record) => {
              return {
                onClick: () => {},
                onDoubleClick: () => {
                  setCurrent(record);
                },
              };
            }}
          />
        </TabPane>
        <TabPane tab={intl.formatMessage({ id: 'pages.fieldSettings' })} key="2" forceRender>
          <Form {...layout} ref={formRef} onFinish={onFinish}>
            <Row gutter={16}>
              <Col span={15}>
                <Form.Item name="id" label="ID" hidden>
                  <Input />
                </Form.Item>
                <Form.Item
                  name="dataIndex"
                  label={intl.formatMessage({ id: 'pages.fieldName' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.fieldNameRequired' }) }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="title"
                  label={intl.formatMessage({ id: 'pages.displayName' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.displayNameRequired' }) }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item name="align" label={intl.formatMessage({ id: 'pages.align' })}>
                  <Select>
                    <Select.Option value="left" key="left">
                      {intl.formatMessage({ id: 'pages.alignLeft' })}
                    </Select.Option>
                    <Select.Option value="center" key="center">
                      {intl.formatMessage({ id: 'pages.alignCenter' })}
                    </Select.Option>
                    <Select.Option value="right" key="right">
                      {intl.formatMessage({ id: 'pages.alignRight' })}
                    </Select.Option>
                  </Select>
                </Form.Item>
                <CateSelect
                  layout="FieldType"
                  width={200}
                  name="valueType"
                  label={intl.formatMessage({ id: 'pages.fieldType' })}
                  required
                  rules={[
                    {
                      required: true,
                      message: <FormattedMessage id="pages.selectValueType" />,
                    },
                  ]}
                />
                <Form.Item name="width" label={intl.formatMessage({ id: 'pages.width' })}>
                  <InputNumber min={10} />
                </Form.Item>
                <Form.Item name="order" label={intl.formatMessage({ id: 'pages.columnOrder' })}>
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item name="format" label={intl.formatMessage({ id: 'pages.dataFormat' })}>
                  <Input />
                </Form.Item>
                <Form.Item name="dictname" label={intl.formatMessage({ id: 'pages.dictionaryName' })}>
                  <Select>
                    {dicType?.map((item: any) => {
                      return (
                        <Select.Option key={item.label} value={item.value}>
                          {item.label}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 5 }}>
                  <Space>
                    <Button type="primary" htmlType="submit" loading={loading}>
                      {intl.formatMessage({ id: 'pages.save' })}
                    </Button>
                    <Button type="default" loading={loading} onClick={newData}>
                      {intl.formatMessage({ id: 'pages.new' })}
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
              <Col span={9}>
                <Form.Item name="ellipsis" label={intl.formatMessage({ id: 'pages.autoFit' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="hideInTable" label={intl.formatMessage({ id: 'pages.hideColumn' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="hideInSearch" label={intl.formatMessage({ id: 'pages.hideSearch' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="sorter" label={intl.formatMessage({ id: 'pages.columnSort' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="filters" label={intl.formatMessage({ id: 'pages.columnFilter' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="copyable" label={intl.formatMessage({ id: 'pages.copyable' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name="editable" label={intl.formatMessage({ id: 'pages.editable' })} valuePropName="checked">
                  <Checkbox />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </TabPane>
      </Tabs>
    </>
  );
};

export default DataDesignForm;
